package com.cbs.android.module.shit;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

import com.cbs.android.component.application.activity.CBSActivity;
import com.cbs.android.component.application.activity.handler.CBSActivityLifeCyclerHandler;
import com.cbs.android.component.log.L;

import java.lang.ref.WeakReference;
import java.util.HashMap;

/**
 * Created by broche on 7/14/16.
 */
public class ShitModule {
    private static final String TAG = ShitModule.class.getName();
    private static boolean debug = false;
    private static int interval = 30 * 1000;
    private static HashMap<WeakReference<CBSActivity>, ShitModuleListener> listeners = new HashMap<>();

    public static boolean isDebug() {
        return debug;
    }

    public static void setDebug(boolean debug) {
        ShitModule.debug = debug;
    }

    public static int getInterval() {
        return interval;
    }

    public static void setInterval(int interval) {
        ShitModule.interval = interval;
    }

    public static HashMap<WeakReference<CBSActivity>, ShitModuleListener> getListeners() {
        return listeners;
    }

    public static void bind(CBSActivity activity, ShitModuleListener listener) {
        Intent intent = new Intent(activity, ShitService.class);
        listeners.put(new WeakReference<>(activity), listener);
        MyServiceConnection connection = new MyServiceConnection(listener);
        activity.addDestroyHandler(new ShitDestroyHandler(connection));
        activity.bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }

    private static class MyServiceConnection implements ServiceConnection {
        private ShitModuleListener listener;

        public MyServiceConnection(ShitModuleListener listener) {
            this.listener = listener;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            L.e(TAG, "module.service connected");
            listener.onBinded(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
//            if (listeners.values().contains(listener)) {
//                listeners.remove(listener);
//            }
        }
    }

    private static class ShitDestroyHandler implements CBSActivityLifeCyclerHandler {
        private MyServiceConnection connection;

        public ShitDestroyHandler(MyServiceConnection connection) {
            this.connection = connection;
        }

        @Override
        public void handler(CBSActivity cbsActivity) {
            L.e(TAG, "module.destroyhandler");
            cbsActivity.unbindService(connection);
            cbsActivity.removeDestroyHandler(this);
        }
    }
}
